/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-08-17 16:55:09
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-04-16 16:13:22
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { getDictTypeOptionselect } from '@/api/system/dictType';
import { DictTypeType } from '@/type.d/system';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { Tooltip } from 'antd';
import { MenuOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react'
import { useGetResizeHeight } from './useGetResizeTable';
import type { SortableContainerProps, SortEnd } from 'react-sortable-hoc';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import {arrayMoveImmutable} from 'array-move';
import './index.less'

type DataSourceType = {
    columnId: React.Key;
    tableId?: string;
    columnName?: string;
    columnComment?: string;
    columnType?: string;
    javaType?: string;
    javaField?: string;
    isPk?: string;
    isIncrement?: string;
    isRequired?: string;
    isInsert?: string;
    isEdit?: string;
    isList?: string;
    isQuery?: string;
    queryType?: string;
    htmlType?: string;
    dictType?: string;
    sort?: string;
};

export type GenEditTableProps = {
    defaultData: DataSourceType[],
    onValuesChange?: (changedValues: DataSourceType[], record: DataSourceType) => void
}

const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
    <tr {...props} />
));
const SortableBody = SortableContainer((props: React.HTMLAttributes<HTMLTableSectionElement>) => (
    <tbody {...props} />
));



const GenEditTable: React.FC<GenEditTableProps> = (Props) => {
    const [statusOptions, setStatusOptions] = useState<any>([]);
    useEffect(() => {
        getDictTypeOptionselect().then((res) => {
            if (res && res.data) {
                const datas: DictTypeType[] = res.data;
                const opts: Record<string, string> = {};
                datas.forEach((item: DictTypeType) => {
                    opts[item.dictType] = item.dictName;
                });
                setStatusOptions(opts);
            }
        });
    }, [])

    const { defaultData, onValuesChange } = Props;

    const [tableHeight] = useGetResizeHeight('edit-resize-table');

    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
        defaultData.map((item) => item.columnId),
    );
    const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);

    const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
        console.log('oldIndex: ', oldIndex,'newIndex',newIndex);
        if (oldIndex !== newIndex) {
        //   const newData = arrayMoveImmutable({array: dataSource.slice(), fromIndex: oldIndex, toIndex: newIndex}).filter(
          const newData = arrayMoveImmutable(dataSource.slice(),oldIndex,newIndex).filter(
            (el: DataSourceType) => !!el,
          );
          console.log('Sorted items: ', newData);
          setDataSource(newData);
          onValuesChange?.(newData,newData[newIndex])
        }
      };
    
      const DraggableContainer = (props: SortableContainerProps) => (
        <SortableBody
          useDragHandle
          disableAutoscroll
          helperClass="row-dragging"
          onSortEnd={onSortEnd}
          {...props}
        />
      );
    
      const DraggableBodyRow: React.FC<any> = ({ className, style, ...restProps }) => {
        const index = dataSource.findIndex(x => x.columnId === restProps['data-row-key']);
        return <SortableItem index={index} {...restProps} />;
      };


    const columns: ProColumns<DataSourceType>[] = [
        {
            title: '排序',
            dataIndex: 'sort1',
            readonly: true,
            width: '55px',
            className: 'drag-visible',
            renderText: () => <DragHandle />,
        },
        {
            title: '字段描述',
            readonly: true,
            key: 'columnComment',
            dataIndex: 'columnComment',
            ellipsis: true,
            className: 'drag-visible',
        },
        {
            title: '字段列名',
            readonly: true,
            key: 'columnName',
            dataIndex: 'columnName',
            ellipsis: true
        },
        {
            title: '物理类型',
            readonly: true,
            key: 'columnType',
            dataIndex: 'columnType',
            valueType: 'text',
        },
        {
            title: 'JAVA类型',
            dataIndex: 'javaType',
        },
        {
            title: 'JAVA属性',
            dataIndex: 'javaField',
        },
        {
            title: '插入',
            dataIndex: 'isInsert',
            valueType: 'radio',
            valueEnum: {
                1: { text: '是', status: 'Default' },
                2: { text: '否', status: 'Default' },
            }

        },
        {
            title: '编辑',
            dataIndex: 'isEdit',
            valueType: 'radio',
            valueEnum: {
                1: { text: '是', status: 'Default' },
                2: { text: '否', status: 'Default' },
            }
        },
        {
            title: '列表',
            dataIndex: 'isList',
            valueType: 'radio',
            valueEnum: {
                1: { text: '是', status: 'Default' },
                2: { text: '否', status: 'Default' },
            }
        },
        {
            title: '查询',
            dataIndex: 'isQuery',
            valueType: 'radio',
            valueEnum: {
                1: { text: '是', status: 'Default' },
                2: { text: '否', status: 'Default' },
            }
        },
        {
            title: '查询方式',
            dataIndex: 'queryType',
            valueType: 'select',
            valueEnum: {
                EQ: { text: '=', status: 'Default' },
                NE: { text: '!=', status: 'Default' },
                GT: { text: '>', status: 'Default', },
                GTE: { text: '>=', status: 'Default', },
                LT: { text: '<', status: 'Default', },
                LTE: { text: '<=', status: 'Default', },
                LIKE: { text: 'LIKE', status: 'Default', },
                BETWEEN: { text: 'BETWEEN', status: 'Default', },
            }
        },
        {
            title: '必填',
            dataIndex: 'isRequired',
            valueType: 'radio',
            valueEnum: {
                1: { text: '是', status: 'Default' },
                2: { text: '否', status: 'Default' },
            }
        },
        {
            title: '显示类型',
            dataIndex: 'htmlType',
            valueType: 'select',
            valueEnum: {
                input: { text: '文本框', status: 'Default' },
                textarea: { text: '文本域', status: 'Default' },
                select: { text: '下拉框', status: 'Default', },
                radio: { text: '单选框', status: 'Default', },
                checkbox: { text: '复选框', status: 'Default', },
                datetime: { text: '日期控件', status: 'Default', },
                imageUpload: { text: '图片上传', status: 'Default', },
                fileUpload: { text: '文件上传', status: 'Default', },
                editor: { text: '富文本控件', status: 'Default', },
            }
        },
        {
            title: '字典类型',
            dataIndex: 'dictType',
            valueType: 'select',
            valueEnum: statusOptions
        },
    ];

    return (
        <div id="edit-resize-table">
            <EditableProTable<DataSourceType>
                scroll={
                    { y: tableHeight, }
                }
                bordered={true}
                size="small"
                pagination={false}
                columns={columns}
                rowKey="columnId"
                value={dataSource}
                recordCreatorProps={false}
                onValuesChange={onValuesChange}
                components={{
                    body: {
                      wrapper: DraggableContainer,
                      row: DraggableBodyRow,
                    },
                  }}
                editable={{
                    editableKeys,
                    actionRender: (row, config, defaultDoms) => {
                        return [defaultDoms.delete];
                    },
                    onValuesChange: (record, recordList) => {
                        setDataSource(recordList);
                    },
                    onChange: setEditableRowKeys,
                }}
            />
        </div>
    );
}
export default GenEditTable;